<template>
    <section class="cicd-additem">
<el-form ref="newItemData" :model="newItemData" label-width="93px" :rules="addDeployTaskRules" size="small">
    <el-form-item label="项目名" required prop="name">
        <el-col :span="4">
            <el-input v-model="newItemData.name"></el-input>
        </el-col>

    </el-form-item>
    <el-form-item label="项目描述">
        <el-col :span="16">
        <el-input v-model="newItemData.describe"  type="textarea" :rows="2"></el-input>
        </el-col>
    </el-form-item>
    <el-form-item label="git源码" required prop="giturl">
        <el-col :span="16">
        <el-input v-model="newItemData.giturl"></el-input>
        </el-col>
    </el-form-item>
    <el-form-item label="分支" required prop="branch">
        <el-col :span="4">
            <el-input v-model="newItemData.branch"></el-input>
        </el-col>

    </el-form-item>

    <el-form-item label="代码环境" required prop="lang">
        <el-radio-group v-model="newItemData.lang">
            <el-radio label="java">Jdk</el-radio>
            <el-radio label="golang">Golang</el-radio>
            <el-radio label="python">Python</el-radio>
            <el-radio label="php">Php</el-radio>
        </el-radio-group>
    </el-form-item>

        <el-form-item label="编译" >
            <el-col :span="8">
                <el-input v-model="newItemData.compile"></el-input>
            </el-col>

        </el-form-item>



    <el-form-item label="部署策略" required prop="deploymode">
        <el-select v-model="newItemData.deploymode" placeholder="请选择活动区域" @change="clearDoc">
            <el-option label="ansible 部署" value="ansible"></el-option>

            <el-option label="K8s 集群" value="k8s"></el-option>

        </el-select>
    </el-form-item>

    <div v-if="newItemData.deploymode === 'ansible'">

        <el-form-item label="服务器组" required prop="hosts">
            <el-select v-model="newItemData.hosts" placeholder="请选择负载集群" @focus="chooseHosts">
                <el-option
                        v-for="item in newItemData.options"
                        :label="item.name"
                        :value="item.name">
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="Ansible-yaml"  prop="yamlSyntaxCheck"
        >
            <el-col :span="16">
                <edit-yaml ></edit-yaml>
            </el-col>
        </el-form-item>


    </div>

    <div v-if="newItemData.deploymode === 'k8s'">
        <!--<el-form-item label="">-->
            <!--<el-tag type="success">Docker 配置</el-tag>-->
        <!--</el-form-item>-->
        <el-form-item label="image" prop="imageRule">
            <el-row >
                <el-col :span="12"><el-input v-model="newItemData.imageUrl" placeholder="Repositoriy:habor.company.net"></el-input></el-col>
                <el-col :span="4">
                    <!--<el-input v-model="newItemData.imageVersion" placeholder="Version:latest "></el-input>-->
                    <el-select v-model="newItemData.imageVersion" placeholder="tagPolicy" style="width: 100%">
                        <el-option
                                label="DateTime"
                                value="DateTime"

                        >
                            <span style="float: left">DateTime</span>
                            <span style="float: right; color: #8492a6; font-size: 10px">2006-01-02-15-04-05</span>
                        </el-option>
                        <el-option
                                label="BuildNumber"
                                value="BuildNumber"
                                disabled
                        >
                            <span style="float: left">BuildNumber</span>
                            <span style="float: right; color: #8492a6; font-size: 10px">13</span>
                        </el-option>
                        <el-option
                                label="latest"
                                value="latest"
                        >
                        </el-option>
                    </el-select>
                </el-col>
            </el-row>
        </el-form-item>
        <el-form-item label="Dockerfile" prop="DockerfileRule">
            <el-col :span="16">
            <edit-yaml ></edit-yaml>
            </el-col>
        </el-form-item>
        <el-form-item label="K8s 部署" prop="deploymentYamlCheckRule">

            <el-row >
                <el-col :span="4">
                    <el-select v-model="newItemData.k8stemplate" placeholder="请选择活动区域" style="width: 100%" @change="editBtndisable = false">
                        <el-option-group
                                v-for="group in k8sDeploymentTemplateOptions"
                                :key="group.label"
                                :label="group.label">
                            <el-option
                                    v-for="item in group.options"
                                    :label="item.label ? item.label : item.name"
                                    :value="item.value ? item.value : item.path"
                                    :disabled="item.disabled">
                            </el-option>
                        </el-option-group>
                </el-select>
                </el-col>
                <el-col :span="1"><el-button type="warning" size="mini" style="margin-left: 5px" @click="editK8sDeploymentYaml" :disabled="editBtndisable">编辑</el-button></el-col>
                <el-col :span="1"><el-button type="default" size="mini" style="margin-left: 5px" @click="dialogK8sDeploymentYamlFormVisible = true" >Deployment Yaml</el-button></el-col>
                <el-dialog title="K8s-Deployment" :visible.sync="dialogK8sYamlFormVisible">
                    <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 25}" v-model="K8sYamlContent">


                    </el-input>
                    <span style="color: red;font-size: 8px" v-if="K8sYamlContentErrorVisible">{{K8sYamlContentErrorMessage}}</span>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogK8sYamlFormVisible = false">取 消</el-button>
                        <el-button type="primary" @click="yamlRender">渲 染</el-button>
                    </div>
                </el-dialog>

                <el-dialog title="Deployment-Yaml" :visible.sync="dialogK8sDeploymentYamlFormVisible">
                    <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 25}" v-model="K8sDeploymentYamlContent" readonly>

                    </el-input>
                </el-dialog>

            </el-row>
        </el-form-item>
    </div>

    <el-form-item>
        <el-button type="primary" @click="addDeployHandel('newItemData')">提交</el-button>
        <el-button @click="closeThisTab">取消</el-button>
    </el-form-item>
</el-form>

    </section>
</template>
<script>
    import editYaml from '../../components/edit/edityaml300.vue'
    import { getHostList,AddDeployItem,getDeploymentTemplateLists,LoadTemplateFile } from '../../api/api'
    import $ from 'jquery' //引入jquery 检测输入yaml内容是否格式错误
    import jsyaml from  '../../assets/js/js-yaml.min'

    export default {
        data() {
            var yamlCheckPass = (rule, value, callback) => {

                var cm = $(".yamlcode300  .CodeMirror")[0].CodeMirror;  //怕多个codemirror引起的混乱
                var doc = cm.getDoc();
                let content = doc.getValue().toString()

                if (content.trim() === '') {
                    callback(new Error('请输入ansible-playbook yaml格式脚本内容'));
                } else {
                   try {
                       let dropcontent = jsyaml.load(content);
                       dropcontent= ""
                       callback()

                   }catch (e) {
                       callback(new Error('格式错误： ' + e.message));
                   }
                }

            };
            var imageCheck = (rule, value, callback) => {
                let self = this
                if (self.newItemData.imageUrl === '') {
                    callback(new Error('请输入image地址'));
                } else if (self.newItemData.imageVersion === '') {
                    callback(new Error('请选择镜像Tag'));
                } else {
                    callback()
                }

            };
            var DockerfileCheck = (rule, value, callback) => {

                var cm = $(".yamlcode300  .CodeMirror")[0].CodeMirror;  //怕多个codemirror引起的混乱
                var doc = cm.getDoc();
                let content = doc.getValue().toString()

                if (content.trim() === '') {
                    callback(new Error('请输入Dockerfile'));
                } else {
                    callback()
                }

            };
            var deploymentYamlCheck = (rule, value, callback) => {
                let content = this.K8sDeploymentYamlContent

                if (content.trim() === '') {
                    callback(new Error('请编辑模板'));
                } else {
                    try {
                        let dropcontent = jsyaml.load(content);
                        dropcontent= ""
                        callback()

                    }catch (e) {
                        callback(new Error('格式错误： ' + e.message));
                    }
                }

            };
            return {
                newItemData: {
                    name: '',
                    describe: "",
                    giturl: "",
                    branch: "",
                    lang: "",  //为啥不能用"Jdk"
                    compile: "",


                    deploymode: 'ansible',
                    hosts: '',
                    options: [],
                    ansibleContent: "",  //ansible 部署


                    // k8stemplate: '',
                    // date1: '',
                    // date2: '',
                    // delivery: false,
                    // type: [],
                    // resource: '',
                    // desc: '',
                    imageUrl: "habor.company.com/test",
                    imageVersion: "DateTime",
                    Dockerfile: "",
                    k8sYamlContent: "",
                },
                addDeployTaskRules: {
                    name: [
                        { required: true, message: '请输入项目名-英文字母', trigger: 'blur' },
                    ],
                    giturl: [
                        { required: true, message: '请输入项目地址', trigger: 'blur' },

                    ],
                    branch: [
                        { required: true, message: '请输入项目分支', trigger: 'blur' },

                    ],
                    lang: [
                        { required: true, message: '请选择源码类型', trigger: 'change' }
                    ],
                    deploymode: [
                        { required: true, message: '请选择部署方式', trigger: 'change' }
                    ],
                    hosts: [
                        { required: true, message: '请选择服务组', trigger: 'change' }
                    ],
                    yamlSyntaxCheck: [
                        { validator: yamlCheckPass, trigger: 'blur'}
                    ],

                    //k8s mode
                    imageRule: [
                        { required: true,validator: imageCheck, trigger: 'blur'}

                    ],
                    DockerfileRule: [
                        { validator: DockerfileCheck, trigger: 'blur'}
                    ],
                    deploymentYamlCheckRule: [
                        { validator: deploymentYamlCheck, trigger: 'blur'}
                    ],

                },
                k8sDeploymentTemplateOptions: [
                    {
                        label: 'Deployment Template',
                        options: []
                    } ],

                editBtndisable: true,
                dialogK8sYamlFormVisible: false,
                K8sYamlContent: "",

                K8sDeploymentYamlContent: "",
                dialogK8sDeploymentYamlFormVisible: false,

                K8sYamlContentErrorMessage: "",
                K8sYamlContentErrorVisible: false,

            }
        },
        methods: {
            addDeployHandel(formName) {
                console.log("debug here")

                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        var cm = $(".yamlcode300  .CodeMirror")[0].CodeMirror;  //怕多个codemirror引起的混乱
                        var doc = cm.getDoc();
                        this.newItemData.ansibleContent = doc.getValue().toString()
                        let itemparam = {}
                        if (this.newItemData.deploymode === "ansible") {
                            itemparam = {
                                name: this.newItemData.name,
                                deploymode: this.newItemData.deploymode,
                                describe: this.newItemData.describe,
                                giturl : this.newItemData.giturl,
                                branch : this.newItemData.branch,
                                codelang :this.newItemData.lang,
                                compile : this.newItemData.compile,

                                hosts : this.newItemData.hosts,
                                yamlcontent: this.newItemData.ansibleContent

                            }
                        } else {
                             itemparam = {
                                name: this.newItemData.name,
                                deploymode: this.newItemData.deploymode,
                                describe: this.newItemData.describe,
                                giturl : this.newItemData.giturl,
                                branch : this.newItemData.branch,
                                codelang :this.newItemData.lang,
                                compile : this.newItemData.compile,

                                imageUrl : this.newItemData.imageUrl,
                                imageTag: this.newItemData.imageVersion,
                                dockerfileContent: doc.getValue().toString(),
                                yamlcontent: this.K8sDeploymentYamlContent,

                            }
                        }
                        console.log("nimabide")

                        AddDeployItem(itemparam).then((res) => {
                            console.log("debug here")
                            console.log(res.code)
                            if (res.code === 400) {
                                this.$message({
                                    message: "Warning: 提交失败 " + res.message ,
                                    type: 'success',
                                    duration: 1000,
                                });
                            }else {
                                this.$message({
                                    message: " 提交成功 "  ,
                                    type: 'success',
                                    duration: 1000,
                                });

                                this.$emit('close_tab')
                            }
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });






            },
            chooseHosts(){
                getHostList().then((res) => {
                        console.log(res.data.hosts)
                        this.newItemData.options = res.data.hosts
                    }
                )
            },
            closeThisTab() {
                this.$emit('close_tab')
            },
            getAllDeploymentTemplate(){
                getDeploymentTemplateLists().then((res) => {
                        //this.ipALL = res.data.iplists
                        // console.log(res.data.path)
                        this.k8sDeploymentTemplateOptions[0].options = res.data.path
                    console.log(res.data.path)
                    }
                )
            },
            editK8sDeploymentYaml() { //远程加载模板文件
                let self = this
                if (self.newItemData.k8stemplate.substring(1,9) === "template") {
                    let paramUrl =  self.newItemData.k8stemplate
                    LoadTemplateFile(paramUrl).then((res) => {
                            // console.log(res)
                            self.K8sYamlContent = res

                        }

                    )

                }
                self.dialogK8sYamlFormVisible = true
                self.K8sYamlContentErrorVisible = false

            },
            yamlRender() {
                let self = this
                self.K8sYamlContent = self.K8sYamlContent.replace(/image:.*\n?/,'image: {{projectImageUrl}}\n')
                try {
                    let dropcontent = jsyaml.load(self.K8sYamlContent);
                    dropcontent= ""
                    self.K8sDeploymentYamlContent = self.K8sYamlContent    //只有渲染并检测语法成功后赋值
                    self.dialogK8sYamlFormVisible = false

                }catch (e) {
                    self.K8sYamlContentErrorVisible = true
                    self.K8sYamlContentErrorMessage = e.message
                }

            },
            clearDoc(){
                var cm = $(".yamlcode300  .CodeMirror")[0].CodeMirror;  //怕多个codemirror引起的混乱
                var doc = cm.getDoc();
                doc.setValue("")
            }


        },
        mounted() {
            this.getAllDeploymentTemplate();
        },
        components: {
            editYaml,
        },

    }
</script>
<style>
    .cicd-additem .hosts-select {
        margin-top:5px;
        margin-bottom:5px;
    }
    .cicd-additem .el-dialog__body {
        padding: 10px 20px;
    }
</style>